import React, { Component } from 'react'
import { Flex, WingBlank, WhiteSpace, Toast } from 'antd-mobile'
import { withFormik, Form, Field, ErrorMessage } from 'formik'
import * as Yup from 'yup'
import {API, setToken} from '../../utils'
import { Link } from 'react-router-dom'

import NavHeader from '../../components/NavHeader'

import styles from './index.module.css'

// 验证规则：
const REG_UNAME = /^[a-zA-Z_\d]{5,8}$/
const REG_PWD = /^[a-zA-Z_\d]{3,12}$/

class Registe extends Component {
  render() {
    return (
      <div className={styles.root}>
        {/* 顶部导航 */}
        <NavHeader className={styles.navHeader}>注册</NavHeader>
        <WhiteSpace size="xl" />
        <WingBlank>
          <Form>
            <div className={styles.formItem}>
              <label className={styles.label}>用户名</label>
              <Field className={styles.input}
                name="username"
                placeholder="请输入账号" />
            </div>
            <ErrorMessage className={styles.error} name="username" component="div"></ErrorMessage>
            <div className={styles.formItem}>
              <label className={styles.label}>密码</label>
              <Field
                className={styles.input}
                name="password"
                type="password"
                placeholder="请输入密码"
              />
            </div>
            <ErrorMessage className={styles.error} name="password" component="div"></ErrorMessage>
            <div className={styles.formItem}>
              <label className={styles.label}>重复密码</label>
              <Field
                className={styles.input}
                name="rePassword"
                type="password"
                placeholder="请重新输入密码"
              />
            </div>
            <ErrorMessage className={styles.error} name="rePassword" component="div"></ErrorMessage>
            <div className={styles.formSubmit}>
              <button className={styles.submit} type="submit">
                注册
              </button>
            </div>
          </Form>
          <Flex className={styles.backHome} justify="between">
            <Link to="/layout">点我回首页</Link>
            <Link to="/login">已有账号，去登录</Link>
          </Flex>
        </WingBlank>
      </div>
    )
  }
}

// formik 重构登录表单
Registe = withFormik({
  mapPropsToValues: () => ({ username: '',password: '',rePassword: ''}),
     // 添加表单校验规则 --- yup
  validationSchema: Yup.object().shape({
    username: Yup.string()
      .required('账号为必填项')
      .matches(REG_UNAME, '长度为5到8位，只能出现数字、字母、下划线'),
    password: Yup.string()
      .required('密码为必填项')
      .matches(REG_PWD, '长度为5到12位，只能出现数字、字母、下划线'),
    rePassword: Yup.string()
      .required('密码为必填项')
      // .matches(REG_PWD, '长度为5到12位，只能出现数字、字母、下划线'),
      .oneOf([Yup.ref('password'), null], '密码不一致')
  }),

   handleSubmit: async (values, { props }) => {
    //  console.log(values, props);
    const { username, password } = values
    const res = await API.post('/user/registered', {
       username,
       password
    })
    //  console.log(res);
    const { description, status } = res.data
     if (status === 200) {
      const res = await API.post('/user/login', {
        username, 
        password
     })
      // console.log(res.data.body.token);
       const { body, description, status } = res.data
        // 判断是否登录成功
    if (status === 200) {
      // 登录成功后的操作
      // 把token存储到本地
      // localStorage.setItem('hkzf_token', JSON.stringify(body.token));
      setToken(body.token)
      // // 路由返回到上一页
      // props.history.go(-1)


        props.history.replace('/layout/profile')
      

    } else {
      // 登录失败进行提示
      Toast.info(description, 2 , null ,false)
    }
     } else {
      //  注册失败
       Toast.info(description,2,null, false)
    }
  },

  displayName: 'BasicRegisteForm',
})(Registe);

export default Registe
